package com.dede.monochromatism.base

import android.content.SharedPreferences
import android.os.Bundle
import android.preference.Preference
import android.preference.PreferenceFragment
import android.view.View
import android.widget.ListView
import com.dede.applib.util.LogExtends
import com.dede.applib.util.d
import org.jetbrains.anko.defaultSharedPreferences
import org.jetbrains.anko.dip

/**
 * @author hsh
 * @time 2017/7/25 025 下午 12:44.
 * @doc
 */
abstract class BasePreferenceFragment<T> : PreferenceFragment(), SharedPreferences.OnSharedPreferenceChangeListener,
        Preference.OnPreferenceClickListener, LogExtends {

    open val sp by lazy { defaultSharedPreferences }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        d("onCreate")
    }

    lateinit var contentView: View

    private var viewCreated = false
    private var shouldLoad = false

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        d("onViewCreated")

        contentView = view
        val listView = contentView.findViewById(android.R.id.list) as ListView
        listView.dividerHeight = dip(.8f)

        viewCreated = true
        if (shouldLoad)
            loadDate(this.date)
    }

    override fun onStart() {
        super.onStart()
        sp.registerOnSharedPreferenceChangeListener(this)
    }

    override fun onStop() {
        super.onStop()
        sp.unregisterOnSharedPreferenceChangeListener(this)
    }

    protected var date: T? = null

    fun initDate(date: T?) {
        this.date = date
        if (!viewCreated) {
            shouldLoad = true
            return
        }
        loadDate(date)
    }

    open protected fun loadDate(date: T?) {
        d("loadDate")
    }

    override fun onDestroy() {
        super.onDestroy()
        d("onDestroy")
    }

}